package zhr.store.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;
import zhr.store.Dto.DishDto;
import zhr.store.common.Result;
import zhr.store.domain.Category;
import zhr.store.domain.Dish;
import zhr.store.domain.DishFlavor;
import zhr.store.service.CategoryService;
import zhr.store.service.DishFlavorService;
import zhr.store.service.DishService;
import java.util.ArrayList;
import java.util.List;


/**
 * 菜品管理
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 分页查询菜品
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result<Page> selectAll(int page, int pageSize, String name) {
        //构建分页插件
        Page<Dish> dishPage = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件
        if (name != null) {
            dishLambdaQueryWrapper.like(Dish::getName, name);
        }
        //添加排序条件
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行查询
        dishService.page(dishPage, dishLambdaQueryWrapper);
        //对象拷贝
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        List<Dish> records = dishPage.getRecords();
        //赋值分类名称
        List<DishDto> list = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            //对象拷贝
            BeanUtils.copyProperties(record, dishDto);
            Long categoryId = record.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category == null) {
                break;
            }
            String categoryName = category.getName();
            dishDto.setCategoryName(categoryName);
            //赋值
            list.add(dishDto);
        }
        dishDtoPage.setRecords(list);
        return Result.success(dishDtoPage);
    }

    /**
     * 添加菜品
     *
     * @return
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PostMapping
    public Result<String> insertDish(@RequestBody DishDto dishDto) {
        //执行添加操作
        dishService.insertDishAndFlavor(dishDto);
        return Result.success("添加成功");
    }

    /**
     * 根据id查询菜品
     */
    @GetMapping("/{id}")
    public Result<DishDto> selectByIdDish(@PathVariable Long id) {
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件
        lambdaQueryWrapper.eq(Dish::getId, id);
        //执行查询
        DishDto dishDto = dishService.selectById(id);
        return Result.success(dishDto);
    }

    /**
     * 根据id修改菜品
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PutMapping
    public Result<String> updateDish(@RequestBody DishDto dishDto) {
        //执行修改
        dishService.updateDish(dishDto);
        return Result.success("修改成功");
    }

    /**
     * 修改库存
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    public Result<String> updateInventory(@RequestBody Dish dish) {
        //执行修改
        dishService.updateById(dish);
        return Result.success("修改成功");
    }

    /**
     * 根据id删除
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @DeleteMapping
    public Result<String> deleteDish(@RequestParam List<Long> ids) {
        dishService.deleteDishAndFlavor(ids);
        return Result.success("删除成功");
    }

    /**
     * 启售
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PostMapping("/status/1")
    public Result<String> openDish(Long[] ids) {
        for (Long id : ids) {
            DishDto dishDto = dishService.selectById(id);
            Integer status = dishDto.getStatus();
            if (status == 1) {
                return Result.error("菜品已启售");
            }
            dishService.updateStatus(id);
        }
        return Result.success("启售成功");
    }

    /**
     * 停售
     */
    @CacheEvict(value = "dishCache",allEntries = true)
    @PostMapping("/status/0")
    public Result<String> banDish(Long[] ids) {
        for (Long id : ids) {
            DishDto dishDto = dishService.selectById(id);
            Integer status = dishDto.getStatus();
            if (status == 0) {
                return Result.error("菜品已停售");
            }
            dishService.updateStatus(id);
        }
        return Result.success("停售成功");
    }

    /**
     * 根据条件查询菜品
     */
    @Cacheable(value = "dishCache",key = "#dish.categoryId + '_' + #dish.name",unless = "#result==null")
    @GetMapping("/list")
    public Result<List<DishDto>> list(Dish dish) {
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //构建查询和排序条件
        if (dish.getCategoryId() != null) {
            //查询启售菜品
            dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
            dishLambdaQueryWrapper.eq(Dish::getCategoryId, dish.getCategoryId());
            //排序条件
            dishLambdaQueryWrapper.orderByAsc(Dish::getPrice)
                    .orderByAsc(Dish::getSort)
                    .orderByDesc(Dish::getUpdateTime);
        }
        if (dish.getName() != null) {
            //查询启售菜品
            dishLambdaQueryWrapper.eq(Dish::getStatus, 1);
            dishLambdaQueryWrapper.like(Dish::getName, dish.getName());
            //排序条件
            dishLambdaQueryWrapper.orderByAsc(Dish::getPrice)
                    .orderByAsc(Dish::getSort)
                    .orderByDesc(Dish::getUpdateTime);
        }
        //执行查询
        List<Dish> dishList = dishService.list(dishLambdaQueryWrapper);
        List<DishDto> dishDtoList = new ArrayList<>();
        for (Dish dishOne : dishList) {
            //对象拷贝
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dishOne, dishDto);
            //获取菜品id
            Long id = dishDto.getId();
            //构建查询条件
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, id);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            //设置属性
            dishDto.setFlavors(dishFlavorList);
            dishDtoList.add(dishDto);
        }
        return Result.success(dishDtoList);
    }
}
